package com.dingwei.superiordiary.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.allen.library.SuperButton;
import com.allen.library.SuperTextView;
import com.dingwei.superiordiary.PayUtils.AliPayUtls;
import com.dingwei.superiordiary.PayUtils.PayInterface;
import com.dingwei.superiordiary.PayUtils.WeChatPayUtils;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.bean.CommodityDetailsBean;
import com.dingwei.superiordiary.bean.MyAddressBean;
import com.dingwei.superiordiary.bean.OrderPayBean;
import com.dingwei.superiordiary.mvp.presenter.FirmOrderPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.utils.Constants;
import com.dingwei.superiordiary.utils.PayResult;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.AppManager;
import com.lihao.baselibrary.utils.L;
import com.lihao.baselibrary.utils.MathUtil;
import com.lihao.baselibrary.weight.TitleBar;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/2/27.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class FirmOrderActivity extends BaseActivity implements Contract.FirmOrderView {

    FirmOrderPresenter firmOrderPresenter = new FirmOrderPresenter(this);
    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.Integral_rule)
    ImageView IntegralRule;
    @Bind(R.id.img_reduce)
    ImageView imgReduce;
    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.img_add)
    ImageView imgAdd;
    @Bind(R.id.price)
    SuperTextView price;
    @Bind(R.id.et_remark)
    EditText etRemark;
    @Bind(R.id.btn_wx_pay)
    SuperButton btnWxPay;
    @Bind(R.id.btn_alipay)
    SuperButton btnAlipay;
    @Bind(R.id.btn_exchange)
    SuperButton btnExchange;
    @Bind(R.id.data_layout)
    LinearLayout dataLayout;

    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_attribute)
    TextView tvAttribute;
    @Bind(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @Bind(R.id.ll_jifen)
    LinearLayout llJifen;

    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.ll_address)
    LinearLayout llAddress;
    @Bind(R.id.tv_integral)
    TextView tvIntegral;
    private String address_id;
    CommodityDetailsBean.DataBean bean;
    String attribute;
    String attributeStr;
    double attribute_price;
    int stock;
    int num;
    String id;
    IWXAPI api;
    private boolean isShare;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_firm_order;
    }

    @Override
    protected void initData() {
        if (bean.default_address!=null&&!TextUtils.isEmpty(bean.default_address.address)){
            address_id = bean.default_address.id;
            tvAddress.setText(bean.default_address.name + " " + bean.default_address.mobile + " " + bean.default_address.province + bean.default_address.city + bean.default_address.county + bean.default_address.address);
            tvAddress.setTextColor(getResources().getColor(R.color.text_color_black));
        }else {
            tvAddress.setText("添加地址");
            tvAddress.setTextColor(getResources().getColor(R.color.theme_color));
        }

    }

    @Override
    protected void initView() {
        bean = (CommodityDetailsBean.DataBean) getIntent().getSerializableExtra("bean");
        stock = bean.stock;

        if (getIntent().hasExtra("stock")){
            stock = getIntent().getIntExtra("stock",0);
        }
        attribute = getIntent().getStringExtra("attribute");
        attributeStr = getIntent().getStringExtra("attributeStr");
        id = getIntent().getStringExtra("id");
        attribute_price = getIntent().getDoubleExtra("price",0);
        num = getIntent().getIntExtra("num", 1);
        isShare = getIntent().getBooleanExtra("isShare",false);
        if (bean.is_integral.equals("1")) {
            llJifen.setVisibility(View.GONE);
            btnExchange.setVisibility(View.GONE);

            tvName.setText(bean.name);
            if (attribute==null||TextUtils.isEmpty(attribute)) {
                tvAttribute.setText("标准规格");
            } else {
                tvAttribute.setText(attributeStr);
            }
            if (attribute==null){
                tvGoodsPrice.setText("￥" + MathUtil.trimShu(bean.price + ""));
            }else {
                tvGoodsPrice.setText("￥" + MathUtil.trimShu(attribute_price + ""));
            }
            String freight = "";
            if (bean.freight == 0) {
                freight = "免运费";
            } else {
                freight = "运费" + MathUtil.trimShu(bean.freight + "") + "元";
            }
            if (attribute==null){
                price.setRightTopString("￥" + MathUtil.trimShu((bean.price * num + bean.freight) + ""))
                        .setRightBottomString(freight).useShape();

            }else {
                price.setRightTopString("￥" + MathUtil.trimShu((attribute_price * num + bean.freight) + ""))
                        .setRightBottomString(freight).useShape();
            }
        } else {

            llJifen.setVisibility(View.VISIBLE);
            tvName.setText(bean.name);
            tvAttribute.setText("标准规格");
            tvGoodsPrice.setText("￥" + bean.price);
            tvIntegral.setText(bean.integral+"");
            String freight = "";
            if (bean.freight == 0) {
                freight = "免运费";
            } else {
                freight = "运费" + MathUtil.trimShu(bean.freight + "") + "元";
            }
            price.setRightTopString("￥" + MathUtil.trimShu((bean.price * num + bean.freight) + ""))
                    .setRightBottomString(freight).useShape();

            double total_price = bean.price * num + bean.freight;
            if (total_price > 0) {
                btnAlipay.setVisibility(View.VISIBLE);
                btnWxPay.setVisibility(View.VISIBLE);
                btnExchange.setVisibility(View.GONE);
            } else {
                btnAlipay.setVisibility(View.GONE);
                btnWxPay.setVisibility(View.GONE);
                btnExchange.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            MyAddressBean.DataBean dataBean = (MyAddressBean.DataBean) data.getSerializableExtra("address_info");
            address_id = dataBean.id;
            tvAddress.setText(dataBean.name + " " + dataBean.mobile + " " + dataBean.province + dataBean.city + dataBean.county + dataBean.address);
            tvAddress.setTextColor(getResources().getColor(R.color.text_color_black));
        }
    }

    @OnClick({R.id.ll_address, R.id.btn_wx_pay, R.id.btn_alipay, R.id.btn_exchange,R.id.img_reduce, R.id.img_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address:
                intent = new Intent(BaseActivity.context, MyAddressActivity.class);
                intent.putExtra("type", "1");
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_wx_pay:
                submitOrder("wx");
                break;
            case R.id.btn_alipay:
                submitOrder("alipay");
                break;
            case R.id.btn_exchange:
                submitOrder("exchange");
                break;
            case R.id.img_reduce:
                num = num - 1;
                if (stock>0){
                    if (num == 0) {
                        num = 1;
                    }
                }else {
                    num = 0;
                }
                tvNum.setText(num+"");

                break;
            case R.id.img_add:
                num = num + 1;
                if (num > stock) {
                    num = stock;
                    showToast("不能大于库存");
                }
                tvNum.setText(num+"");
                break;
        }
    }

    public void submitOrder(String tag){
        if (isShare){
            if (attribute==null||TextUtils.isEmpty(attribute)){
                firmOrderPresenter.payOrder(id, num, bean.freight, bean.price, "", address_id, etRemark.getText().toString().trim(), tag, getIntent().getStringExtra("key"));
            }else {
                firmOrderPresenter.payOrder(id, num, bean.freight, attribute_price, attribute, address_id, etRemark.getText().toString().trim(), tag, getIntent().getStringExtra("key"));

            }
        }else {
            if (attribute==null||TextUtils.isEmpty(attribute)){
                firmOrderPresenter.payOrder(id, num, bean.freight, bean.price, "", address_id, etRemark.getText().toString().trim(), tag, "");
            }else {
                firmOrderPresenter.payOrder(id, num, bean.freight, attribute_price, attribute, address_id, etRemark.getText().toString().trim(), tag, "");

            }
        }
    }


    @Override
    public void wxPay(OrderPayBean bean) {
        WeChatPayUtils.getInstance().setWeChatPay(bean.data.wx, new PayInterface() {
            @Override
            public void paySuccess() {
                intent = new Intent(BaseActivity.context,MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }

            @Override
            public void payError() {
                intent = new Intent(BaseActivity.context,MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }

            @Override
            public void payCancel() {
                intent = new Intent(BaseActivity.context,MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }
        },context);
    }




    @Override
    public void alipay(final OrderPayBean bean) {
        AliPayUtls.getInstance().setAliPay(this, bean.data.zfb, new PayInterface() {
            @Override
            public void paySuccess() {
                intent = new Intent(BaseActivity.context, MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }

            @Override
            public void payError() {
                intent = new Intent(BaseActivity.context, MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }

            @Override
            public void payCancel() {
                intent = new Intent(BaseActivity.context, MyOrderActivity.class);
                startActivity(intent);
                AppManager.getAppManager().finishActivity(EditOrderActivity.class);
                AppManager.getAppManager().finishActivity();
            }
        });
    }



    @Override
    public void exchangeSuccess(OrderPayBean bean) {
        showToast("兑换成功");
        AppManager.getAppManager().finishActivity(EditOrderActivity.class);
        AppManager.getAppManager().finishActivity();
    }


}
